package leetcode.editor.day;

import java.util.Arrays;

// 667. 优美的排列 II
// https://leetcode.cn/problems/beautiful-arrangement-ii/
class BeautifulArrangementIi {
    public static void main(String[] args) {
        Solution solution = new BeautifulArrangementIi().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    // 脑经急转弯
    // https://leetcode.cn/problems/beautiful-arrangement-ii/solution/you-by-capital-worker-rnwi/
    class Solution {
        public int[] constructArray(int n, int k) {
            int i = 0, q = 1, p = n;
            int[] arr = new int[n];
            // k = 4 : 1 6 2 5 4 3
            // 构造前k个数组 k-1个不同的整数
            // 奇数位从大到小，偶数位从小到大
            for (int j = 0; j < k; j++) {
                if (j % 2 == 0) {
                    arr[i++] = q++;
                } else {
                    arr[i++] = p--;
                }
            }

            // 剩下构造绝对值为1的序列
            // k = 2 : 1 6 5 4 3 2 偶数后面降序
            // k = 3 : 1 6 2 3 4 5 奇数后面升序
            if (k % 2 == 0) {
                while (i < n) {
                    arr[i++] = p--;
                }
            } else {
                while (i < n) {
                    arr[i++] = q++;
                }
            }

            return arr;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
